<template>
  <div class="main">
    <es-row :width="1920" :height="100">
      <login-status-view @init="loginInit" :focusable="!isPlaying"/>
      <span v-if="regNumber.length>3" class="home_regNumber"
            :focusable="false">备案号：{{ regNumber }}</span>
    </es-row>
    <es-row :width="1920" :height="980" :justify-content="'space-around'">
      <div class="leftContent">
        <span class="guize-title">游戏规则</span>
        <span class="guize-content">{{guize}}</span>
      </div>
      <div class="layout">
        <es-row>
          <span class="score">步数：{{ -score }}</span>
          <text-button
            :focusable="!isPlaying"
            :text="isPlaying?'按返回结束':'开始游戏'"
            :color="isPlaying?'gray':'green'"
            @click="init" :requestFocus="true"
          ></text-button>
          <span
            class="meRank">排名：{{ meRank ? meRank.rankNum + ' (' + (-meRank.score) + '步)' : '-' }}</span>
        </es-row>
        <div class="all-container">
          <div class="board">
            <!--棋盘-->
            <div v-for="row in 4" :key="row" class="board-row"
            >
              <div v-for="col in 4" :key="col"
                   class="board-col" >
              </div>
            </div>
<!--            棋子-->
            <qt-view v-for="item in 25" v-if="board" ref="boardItem"
                 :focusable="itemFocusable(item)"
                 class="board-item" @click="placeStone(item)"
                 :style="itemStyle(item)"
            />
          </div>
        </div>
      </div>
      <div class="ranklist">
        <s-text-view :font-size="32" text="排行榜"></s-text-view>
        <s-text-view v-for="(item,index) in rankList" :font-size="30"
                     :text="'第'+(index+1)+'名：'+(-item.score)+'步'"></s-text-view>
      </div>
    </es-row>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent} from "@vue/runtime-core";
import {reactive, ref} from "vue";

import EsColumn from "../components/container/EsColumn.vue";
import {ESKeyCode, ESKeyEvent, useESEventBus, useESLog, useESToast} from "@extscreen/es3-core";
import {useESRouter} from "@extscreen/es3-router";
import EsRow from "../components/container/EsRow.vue";
import {__CONFIG__, apiUrl} from "./config/global";
import LoginStatusView from "./LoginStatusView.vue";

import {getAgreementKey}  from "./config/global";
import {WolfAi} from "./types/WolfAi";
export default defineComponent({
  components: {LoginStatusView, EsRow, EsColumn},
  setup() {
    const TAG="Index"
    var toast = useESToast();
    const router = useESRouter()
    const esLog = useESLog();
    const customerNoticeRef = ref()
    const regNumber = __CONFIG__.regNumber + " " + __CONFIG__.IndRegNumber
    var esEventBus = useESEventBus();
    const rankList = ref([])
    const meRank = ref(null)
    const board = ref([
      [0, 2, 2, 2, 0],
      [0, 0, 0, 0, 0],
      [1, 1, 1, 1, 1],
      [1, 1, 1, 1, 1],
      [1, 1, 1, 1, 1] ])
    const boardItem=ref([])
    const posSet=new Set()
    let colorMap = {
      0: 'transparent',
      1: 'white',
      2: 'black'
    }
    const wolfAi=new WolfAi()
    const onESCreate = () => {
      console.log('onESCreate')
      getRankList()
    }
    const score = ref(0)
    const guize='黑色棋子为狼，白色棋子为羊。\n' +
      '狼先手，羊后手。\n' +
      '狼走两格可以吃羊，\n' +
      '也可以走一格。\n' +
      '羊只能走一格。\n' +
      '目标：\n' +
      '狼将羊吃完为狼胜,\n' +
      '羊将狼困住为羊胜。'
    const isPlaying = ref(false)
    const selectList=computed(()=>{
      let moveTo=[]
      if (selectPos.value>0){
        moveTo=wolfAi.getSheepCanMoveTo(board.value,{x:toRow(selectPos.value),y:toCol(selectPos.value)})
      }
      let list=[...wolfAi.getSheepCanMovePos(board.value),
          ...moveTo]
      // console.log(list)
      return list
    })
    const selectPos=ref(0)
    function init() {
      initStatus()
      isPlaying.value = true
      //狼先手
      board.value=wolfAi.wolfStep(board.value)
    }

    function initStatus() {
      score.value = 0
      board.value=[
        [0, 2, 2, 2, 0],
        [0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1]
      ]
      posSet.clear()
    }

    function saveScore(score) {
      if (__CONFIG__.userInfoObj &&
        __CONFIG__.userInfoObj.userId) {
        fetch(apiUrl + "/rank/save", {
          method: 'POST',
          headers: {
            "content-type": "application/json"
          },
          body: JSON.stringify({
            packageName: __CONFIG__.packageName,
            userId: __CONFIG__.userInfoObj.userId,
            score: score,
            nickName: __CONFIG__.userInfoObj.nickName
          })
        }).then(res => res.json()).then(res => {
          if (res.code == 1) {
            meRank.value = res.data
            console.log('rankSave', meRank)
          }
        })
      }

    }

    function onBackPressed() {
      if (isPlaying.value) {
        isPlaying.value = false
      } else {
        router.back()
      }
    }
    function loginInit() {
      if (__CONFIG__.userInfoObj && __CONFIG__.userInfoObj.userId) {
        //获取自己排名
        fetch(apiUrl + "/rank/me?packageName=" + __CONFIG__.packageName + "&userId=" + __CONFIG__.userInfoObj.userId)
          .then(res => res.json())
          .then(res => {
            console.log('meRank', res)
            if (res.code == 1) {
              meRank.value = res.data
            }
          })
      }
    }

    function getRankList() {
      fetch(apiUrl + "/rank/list?packageName=" + __CONFIG__.packageName, {
        method: 'GET'
      }).then(res => res.json())
        .then(res => {
          console.log('rankList', res)
          if (res.code == 1) {
            rankList.value = res.data
          }
        })
    }

    function placeStone(item) {
      //如果当前有棋子则选中
      if (1==board.value[toRow(item)][toCol(item)]){
        selectPos.value=item
      }else{
        if (selectPos.value>0) {
          board.value[toRow(selectPos.value)][toCol(selectPos.value)]=0
          board.value[toRow(item)][toCol(item)]=1
          selectPos.value=0
          score.value--
          let ret=wolfAi.wolfStep(board.value)
          if (ret==null){
            gameOver(1)
            return
          }
          board.value=ret
          if (selectList.value.length==0){
            gameOver(0)
            return
          }
        }
      }
    }
    function gameOver(winner){
      if (isPlaying.value) {
        isPlaying.value = false
        let msg=''
        if(winner==1){
          msg="您赢了!"
        }else{
          msg="您输了!"
        }
        if (winner==1){
          saveScore(score.value)
        }
        router.push({
          name: 'game_over_view',
          params: {
            status: false,
            message: msg+'您的步数是：' + (-score.value)
          }
        })
      }
    }
    function toRow(item){
      return Math.floor((item-1)/5)
    }
    function toCol(item) {
      return (item-1)%5
    }
    function itemStyle(item){
      let row=toRow(item)
      let col=toCol(item)
      let selectColor='#f59e0b'
      let defaultBackgroundColor=colorMap[board.value[row][col]]
      let boardColor='transparent'
      if (item==selectPos.value){
        boardColor=selectColor
      }
      return {
        backgroundColor:defaultBackgroundColor,
        focusBorderColor:selectColor,
        borderColor:boardColor,
        top:row*180+2.5,
        left:col*180+2.5,
      }
    }
    function itemFocusable(item){
      return isPlaying.value&&selectList.value.indexOf(item-1)!=-1
    }
    return {
      onESCreate,
      regNumber,
      score,
      init,
      isPlaying,
      onBackPressed,
      rankList,
      meRank,
      loginInit,
      board,
      placeStone,
      colorMap,
      boardItem,
      selectList,
      itemStyle,
      itemFocusable,
      guize
    }
  }
});
</script>

<style scoped>
.main {
  width: 1920px;
  height: 1080px;
  background-color: #EAEDEF;
}

.title {
  font-size: 64px;
  margin: 20px;
}

.user_level {
  font-size: 32px;
  margin: 20px;
}

.question_seq {
  font-size: 32px;
  margin: 20px;
}

.question_title {
  font-size: 32px;
  margin: 20px;
  font-weight: bold;
}

.direction {
  width: 120px;
  height: 120px;
}

.answer {
  font-size: 64px;
  height: 80px;
}

.left {
  transform: rotate(-90deg);
}

.right {
  transform: rotate(90deg);
}

.down {
  transform: rotate(180deg);
}

.selectStatusInfo {
  font-size: 32px;
}

.home_regNumber {
  position: absolute;
  padding-left: 20px;
  padding-right: 100px;
  width: 1920px;
  height: 32px;
  margin-top: 10px;
  font-size: 24px;
  font-weight: 400;
  color: #000000;
  line-height: 32px;
  background-color: transparent;
}

.score {
  font-size: 32px;
  margin: 20px;
  width: 200px;
  text-align: left;
}

.button-inner {
  font-size: 50px;
  color: #d88288;
  font-weight: bold;
}

.layout {
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  width: 900px;
  height: 900px;
}

.layout .all-container {
  height: 750px;
  width: 750px;
  display:flex;
  justify-content: center;
  align-items: center;
}

.layout .all-container .background {
  box-sizing: content-box;
  background-color: #bbada0;
  display: inline-flex;
  flex-wrap: wrap;
  padding: 10px;
  justify-content: space-between;
  border-radius: 10px;
  width: 720px;
  height: 720px;
  position: absolute;
  z-index: 0;
}

.layout .all-container .background > span {
  background-color: rgba(238, 228, 218, 0.35);
  margin: 12px;
  width: 150px;
  height: 150px;
  border-radius: 10px;
  z-index: 1;
}

.layout .all-container .container {
  z-index: 0;
  padding: 10px;
  width: 720px;
  height: 720px;
  display: inline-flex;
  position: absolute;
  justify-content: flex-start;
  align-items: flex-start;
  -webkit-touch-callout: none;
  -ms-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -ms-touch-action: none;
  touch-action: none;
}

.layout .all-container .container .list {
  margin: 12px;
  width: 150px;
  height: 150px;
  border-radius: 10px;
  position: absolute;
  font-size: 60px;
  font-weight: bold;
  transition-property: transform;
  transition: 100ms ease-in-out;
  color: #fff;
  text-align: center;
}

.leftContent {
  width: 510px;
  height: 900px;

}
.guize-title{
  width: 510px;
  height: 60px;
  padding-left: 20px;
  font-size: 32px;
}
.guize-content{
  width: 510px;
  height: 800px;
  padding-left: 20px;
  font-size: 28px;
}

.ranklist {
  width: 510px;
  height: 900px;
}

.meRank {
  width: 260px;
  text-align: center;
  font-size: 32px;
}

.board {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 760px;
  height: 760px;
  border-width: 1px;
  border-color: black;
  background-color: #bbada0
}
.board-row{
  display:flex;
  flex-direction: row;
}
.board-col{
  width: 180px;
  height: 180px;
  border-width: 1px;
  border-color: black;
  background-color: transparent;
}
.board-item{
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 15px;
  border-width: 2px;
}
</style>
